package com.njg.juc.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author njg
 * @version 1.0
 * @date 2025/4/26 19:50
 */
public class DeadLockDemo {

    private static Lock lockA = new ReentrantLock();
    private static Lock lockB = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            lockA.lock();
            try {
                System.out.println("自己持有锁A,尝试获得锁B");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lockB.lock();
                try {
                    System.out.println("获得锁B");
                } finally {
                    lockB.unlock();
                }
            } finally {
                lockA.unlock();
            }
        }, "A").start();


        new Thread(() -> {
            lockB.lock();
            try {
                System.out.println("自己持有锁B,尝试获得锁A");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                lockA.lock();
                try {
                    System.out.println("获得锁A");
                } finally {
                    lockA.unlock();
                }

            } finally {
                lockB.unlock();
            }
        }, "B").start();
    }
}
